#include <iostream>
#include <thread>
#include <mutex>

using std::cout;
using std::endl;
using std::thread;
using std::mutex;

int gCnt = 0;
mutex mtx;

class MutexLock
{
public:
    MutexLock(mutex &mutx)
    : _mutx(mutx)
    {
        _mutx.lock();//上锁
    }

    ~MutexLock()
    {
        _mutx.unlock();//解锁
    }
private:
    mutex &_mutx;
};

void threadFunc()
{
    for(size_t idx = 0; idx != 10000000; ++idx)
    {
        //利用栈对象的生命周期管理资源，在构造函数中初始化资源，在析构
        //函数中释放资源
        MutexLock autoLock(mtx);
        ++gCnt;
    }
}

int main(int argc, char *argv[])
{
    thread tha(threadFunc);
    thread thb(threadFunc);

    tha.join();
    thb.join();

    cout << "gCnt = " << gCnt << endl;
    return 0;
}

